package com.powernode.controller;


import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;

@Controller
@RequestMapping("download")
public class DownloadController {
    private String rootPath="/upload/";
    /**
     * 文件下载的方法
     */
    @RequestMapping("loadImag.action")
    public void download(String path, HttpServletResponse response) throws Exception{
        File file = new File(rootPath,path); //本地磁盘文件
        //使用输入流 将文件读入内存中
        FileInputStream fis = new FileInputStream(file); //找参照物,将程序运行的内存当作参照物
        byte[] b = new byte[1024];
        int len = -1;
        //输出流，将文件输出到客户端
        ServletOutputStream out = response.getOutputStream();
        //设置响应类型，通知浏览器，不要打开
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        //循环读,循环写
        while ((len = fis.read(b)) != -1) {
            out.write(b, 0, len);
            out.flush();
        }
        out.close();
        fis.close();
    }
}
